<template>
	<view class="container">
		<!-- 相机模块 -->
		<camera v-if="showCamera" class="camera" device-position="back" flash="off" @error="cameraError"></camera>

		<!-- 操作按钮组 -->
		<view class="action-buttons">
			<button class="btn capture-btn" @tap="takePhoto">📷 拍照识别</button>
			<button class="btn album-btn" @tap="openAlbum">🖼️ 相册选图</button>
		</view>

		<!-- 识别结果展示 -->
		<view v-if="resultVisible" class="result-card">
			<image :src="foodImage" class="food-image" mode="widthFix"></image>
			<view class="food-info">
				<text class="food-name">{{ foodName || '未知食物' }}</text>
				<view class="calorie-info">
					<text>🔥 卡路里：{{ calories }} kcal</text>
					<text>⚖️ 分量：{{ weight }}g</text>
				</view>
				<progress :percent="caloriePercent" stroke-width="10" activeColor="#FF6A6A" />
				<text class="hint">占每日推荐摄入 {{ caloriePercent }}%</text>
			</view>
		</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading">
			<activity-indicator size="large" color="#FF6A6A"></activity-indicator>
			<text>识别中...</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				showCamera: true,
				loading: false,
				resultVisible: false,
				foodImage: '',
				foodName: '',
				calories: 0,
				weight: 0,
				caloriePercent: 0,
				token: ''
			}
		},
		onLoad() {
			this.getToken()
		},
		methods: {
			async getToken() {
				const res = await uni.request({
					url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials',
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					data: {
						client_id: 'Q8ccJf7kIW6HBlY1Eyz9rNRZ',
						client_secret: 'hBP49CwSZ2AGENwkzel3W2gUEOSzp6CJ' // 在此处替换实际token
					}
				});
				this.token = res[1].data.access_token
				console.log(this.token, 'this.token')
			},
			// 拍照识别
			takePhoto() {
				this.loading = true;
				const ctx = uni.createCameraContext();
				ctx.takePhoto({
					quality: 'high',
					success: (res) => {
						this.foodImage = res.tempImagePath;
						this.recognizeFood(res.tempImagePath);
					},
					fail: (err) => {
						uni.showToast({
							title: '拍照失败',
							icon: 'none'
						});
						this.loading = false;
					}
				});
			},

			// 打开相册选图
			openAlbum() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album'],
					success: (res) => {
						this.foodImage = res.tempFilePaths[0];
						this.recognizeFood(res.tempFilePaths[0]);
						this.loading = true;
					}
				});
			},

			// 调用AI识别食物
			async recognizeFood(imagePath) {
				let that = this
				try {
					// 1. 图片转Base64
					const base64 = await this.getBase64(imagePath);

					// 2. 调用百度AI接口（需替换成自己的API密钥）
					const res = await uni.request({
						url: 'https://aip.baidubce.com/rest/2.0/image-classify/v2/dish',
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						data: {
							image: base64.replace(/^data:image\/\w+;base64,/, ""),
							access_token: that.token // 在此处替换实际token
						}
					});

					let results = res[1]
					console.log(results, 'sss')
					if (results) {
						const topResult = results.data.result[0];
						this.foodName = topResult.name;
						this.calories = Math.round(topResult.calorie || 0);
						this.weight = topResult.weight || 100;
						this.caloriePercent = Math.min(Math.round(this.calories / 2000 * 100), 100);
						this.resultVisible = true;
					} else {
						uni.showToast({
							title: '未识别到食物',
							icon: 'none'
						});
					}

					// 3. 处理识别结果
					// if (res.data && res.data.result && res.data.result.length > 0) {
					// 	const topResult = res.data.result[0];
					// 	this.foodName = topResult.name;
					// 	this.calories = Math.round(topResult.calorie || 0);
					// 	this.weight = topResult.weight || 100;
					// 	this.caloriePercent = Math.min(Math.round(this.calories / 2000 * 100), 100);
					// 	this.resultVisible = true;
					// } else {
					// 	uni.showToast({
					// 		title: '未识别到食物',
					// 		icon: 'none'
					// 	});
					// }
				} catch (e) {
					uni.showToast({
						title: '识别失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			// 图片转Base64
			getBase64(filePath) {
				return new Promise((resolve, reject) => {
					uni.getFileSystemManager().readFile({
						filePath,
						encoding: 'base64',
						success: res => resolve(`data:image/jpeg;base64,${res.data}`),
						fail: reject
					});
				});
			},

			// 相机错误处理
			cameraError(e) {
				console.error('相机错误:', e.detail);
				uni.showToast({
					title: '相机启动失败，请检查权限',
					icon: 'none'
				});
			}
		}
	}
</script>

<style scoped>
	.container {
		padding: 20rpx;
		background: #f8f9fa;
		min-height: 100vh;
	}

	.camera {
		width: 100%;
		height: 500rpx;
		border-radius: 24rpx;
		margin-bottom: 40rpx;
		box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.1);
	}

	.action-buttons {
		display: flex;
		justify-content: space-around;
		margin: 40rpx 0;
	}

	.btn {
		width: 45%;
		border-radius: 50rpx;
		font-size: 30rpx;
		padding: 20rpx;
	}

	.capture-btn {
		background: linear-gradient(135deg, #FF9A9E, #FAD0C4);
		color: white;
	}

	.album-btn {
		background: linear-gradient(135deg, #A1C4FD, #C2E9FB);
		color: white;
	}

	.result-card {
		background: white;
		border-radius: 24rpx;
		overflow: hidden;
		box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.08);
	}

	.food-image {
		width: 100%;
		height: 400rpx;
		object-fit: cover;
	}

	.food-info {
		padding: 30rpx;
	}

	.food-name {
		font-size: 40rpx;
		font-weight: bold;
		display: block;
		margin-bottom: 20rpx;
		color: #333;
	}

	.calorie-info {
		display: flex;
		justify-content: space-between;
		margin-bottom: 30rpx;
		color: #666;
	}

	.hint {
		display: block;
		text-align: center;
		color: #888;
		font-size: 28rpx;
		margin-top: 15rpx;
	}

	.loading {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(255, 255, 255, 0.8);
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		z-index: 100;
	}
</style>